/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
 */

package com.tcredit.client.sdk.smartu;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaInterfaceImpl;
import org.apache.cordova.CordovaPreferences;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;
import org.apache.cordova.PluginEntry;
import org.apache.cordova.PluginManager;
import org.apache.cordova.engine.SystemWebChromeClient;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewClient;
import org.apache.cordova.engine.SystemWebViewEngine;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

public class MainActivity extends Activity implements WebView.OnClickListener
{
    public static String TAG = "MainActivity";
    private SendDataTask sDataTask = null;
    // The webview for our app
    private CordovaWebView appView;
    private TextView backTv;
    private TextView closeTv;
    private TextView titleTv;
    private ImageView imageView;

//    private ProgressBar progressBar1;
    protected boolean keepRunning = true;
    protected CordovaPreferences preferences;
    protected String launchUrl;
    protected ArrayList<PluginEntry> pluginEntries;
    protected CordovaInterfaceImpl cordovaInterface;

    private Map<String, String> titleMap = new HashMap<String, String>();

    private SystemWebView webView;

    //    private String host = "https://yzj.tcredit.com";
    private String host = "http://test.yzj.tcredit.com";
    private String entName = "";
//    private String host ="http://172.19.160.125:8080";
//    private String host = "http://uat.yzj.tcredit.com";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        loadConfig();

        // enable Cordova apps to be started in the background
        Bundle extras = getIntent().getExtras();
        String userId = UUID.randomUUID().toString();
        String sign = "";
        if (extras != null && extras.containsKey("uid")) {
            userId = extras.getString("uid");
        }
        if (extras != null && extras.containsKey("sign")) {
            sign = extras.getString("sign");
        }

        if (extras != null && extras.containsKey("entName")) {
            entName = extras.getString("entName");
        }



//        String url = "";
//        if (extras != null && extras.containsKey("url")) {
//            url = extras.getString("url");
//        }
//        launchUrl = url +"home/iqiyi/index?uid="+userId+"&sign="+sign;
//        launchUrl = url +"index?uid="+userId+"&sign="+sign;
        launchUrl = host + "/home/"+entName+"/index?uid=" + userId + "&sign=" + sign;
//        launchUrl = "https://yzj.tcredit.com/home/iqiyi/index?uid="+userId+"&sign="+sign;
//        launchUrl = "http://172.19.163.208:9001/iqiyi_client/_contents.html";
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

        super.onCreate(savedInstanceState);

        setContentView(R.layout.toolbar_layout);

//        progressBar1 = (ProgressBar) findViewById(R.id.progressBar1);

        webView = findViewById(R.id.cordovaWebView);

        //禁用缓存
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

        SystemWebViewEngine systemWebViewEngine = new SystemWebViewEngine(webView, preferences);

        webView.setWebChromeClient(new SystemWebChromeClient(systemWebViewEngine) {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (!TextUtils.isEmpty(title)) {
                    String[] strs = title.split("\\.");
                    if (strs.length <= 3 && !title.startsWith("http")) {
                        if (title.length() > 5) {
                            title = title.substring(0, 4) + "...";
                        }
                        String currentUrl = view.getUrl();
                        String cleanUrl = currentUrl.replaceAll("\\#(.*)?", "");
                        titleMap.put(cleanUrl, title);
                        titleTv.setText(title);
                    }
                }
            }

//            @Override
//            public void onProgressChanged(WebView view, int newProgress) {
//                super.onProgressChanged(view, newProgress);
//                if (newProgress == 100) {
//                    progressBar1.setVisibility(View.GONE);
//                } else {
//                    progressBar1.setVisibility(View.VISIBLE);
//                    progressBar1.setProgress(newProgress);
//                }
//            }
        });


        webView.setWebViewClient(new SystemWebViewClient(systemWebViewEngine) {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                String cleanUrl = url.replaceAll("\\#(.*)?", "");
                String str = titleMap.get(cleanUrl);
                if (!TextUtils.isEmpty(str)) {
                    titleTv.setText(str);
                }
            }
        });


        appView = new CordovaWebViewImpl(systemWebViewEngine);
        backTv = findViewById(R.id.textView);
        closeTv = findViewById(R.id.textView2);
        titleTv = findViewById(R.id.textView3);
        imageView = findViewById(R.id.img);
        backTv.setOnClickListener(this);
        closeTv.setOnClickListener(this);
        imageView.setOnClickListener(this);

        cordovaInterface = makeCordovaInterface();
        if (savedInstanceState != null) {
            cordovaInterface.restoreInstanceState(savedInstanceState);
        }
        init();

        sDataTask = new SendDataTask(userId);
        sDataTask.execute((Void) null);

        appView.clearCache();
        loadUrl(launchUrl);
    }

    /**
     * Load the url into the webview.
     */
    public void loadUrl(String url) {
        // If keepRunning
        this.keepRunning = preferences.getBoolean("KeepRunning", true);
        appView.loadUrlIntoView(url, true);
    }

    protected void init() {
        if (!appView.isInitialized()) {
            appView.init(cordovaInterface, pluginEntries, preferences);
        }
        cordovaInterface.onCordovaInit(appView.getPluginManager());

        // Wire the hardware volume controls to control media if desired.
        String volumePref = preferences.getString("DefaultVolumeStream", "");
        if ("media".equals(volumePref.toLowerCase(Locale.ENGLISH))) {
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
        }
    }

    protected void loadConfig() {
        ConfigXmlParser parser = new ConfigXmlParser();
        parser.parse(this);
        preferences = parser.getPreferences();
        preferences.setPreferencesBundle(getIntent().getExtras());
        launchUrl = parser.getLaunchUrl();
        pluginEntries = parser.getPluginEntries();
    }

    protected CordovaInterfaceImpl makeCordovaInterface() {
        return new CordovaInterfaceImpl(this) {
            @Override
            public Object onMessage(String id, Object data) {
                // Plumb this to CordovaActivity.onMessage for backwards compatibility
                return MainActivity.this.onMessage(id, data);
            }
        };
    }

    @Override
    public void onClick(View v) {
        final MainActivity me = this;
        int i = v.getId();
        if (i == R.id.textView || i == R.id.img) {
            if (appView.canGoBack()) {
                appView.getEngine().goBack();
            } else {
                me.finish();
            }
        } else if (i == R.id.textView2) {
            me.finish();
        }

    }

    public Object onMessage(String id, Object data) {
        if ("onReceivedError".equals(id)) {
            JSONObject d = (JSONObject) data;
            try {
                this.onReceivedError(d.getInt("errorCode"), d.getString("description"), d.getString("url"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if ("exit".equals(id)) {
            finish();
        }
        return null;
    }

    public void onReceivedError(final int errorCode, final String description, final String failingUrl) {
        final MainActivity me = this;

        // If errorUrl specified, then load it
        final String errorUrl = preferences.getString("errorUrl", null);
        if ((errorUrl != null) && (!failingUrl.equals(errorUrl)) && (appView != null)) {
            // Load URL on UI thread
            me.runOnUiThread(new Runnable() {
                public void run() {
                    me.appView.showWebPage(errorUrl, false, true, null);
                }
            });
        }
        // If not, then display error dialog
        else {
            final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP);
            me.runOnUiThread(new Runnable() {
                public void run() {
                    if (exit) {
                        me.appView.getView().setVisibility(View.GONE);
                        me.displayError("Application Error", description + " (" + failingUrl + ")", "OK", exit);
                    }
                }
            });
        }
    }

    /**
     * Display an error dialog and optionally exit application.
     */
    public void displayError(final String title, final String message, final String button, final boolean exit) {
        final MainActivity me = this;
        me.runOnUiThread(new Runnable() {
            public void run() {
                try {
                    AlertDialog.Builder dlg = new AlertDialog.Builder(me);
                    dlg.setMessage(message);
                    dlg.setTitle(title);
                    dlg.setCancelable(false);
                    dlg.setPositiveButton(button,
                            new AlertDialog.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    if (exit) {
                                        finish();
                                    }
                                }
                            });
                    dlg.create();
                    dlg.show();
                } catch (Exception e) {
                    finish();
                }
            }
        });
    }
    /**
     * Called when the system is about to start resuming a previous activity.
     */
    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "Paused the activity.");

        if (this.appView != null) {
            // CB-9382 If there is an activity that started for result and main activity is waiting for callback
            // result, we shoudn't stop WebView Javascript timers, as activity for result might be using them
            boolean keepRunning = this.keepRunning || this.cordovaInterface.activityResultCallback != null;
            this.appView.handlePause(keepRunning);
        }
    }

    /**
     * Called when the activity receives a new intent
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //Forward to plugins
        if (this.appView != null)
            this.appView.onNewIntent(intent);
    }

    /**
     * Called when the activity will start interacting with the user.
     */
    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "Resumed the activity.");

        if (this.appView == null) {
            return;
        }
        // Force window to have focus, so application always
        // receive user input. Workaround for some devices (Samsung Galaxy Note 3 at least)
        this.getWindow().getDecorView().requestFocus();

        this.appView.handleResume(this.keepRunning);
    }

    /**
     * Called when the activity is no longer visible to the user.
     */
    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "Stopped the activity.");

        if (this.appView == null) {
            return;
        }
        this.appView.handleStop();
    }

    /**
     * Called when the activity is becoming visible to the user.
     */
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "Started the activity.");

        if (this.appView == null) {
            return;
        }
        this.appView.handleStart();
    }

    /**
     * The final call you receive before your activity is destroyed.
     */
    @Override
    public void onDestroy() {
        Log.d(TAG, "CordovaActivity.onDestroy()");
        super.onDestroy();

        if (this.appView != null) {
            appView.handleDestroy();
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        // Capture requestCode here so that it is captured in the setActivityResultCallback() case.
        cordovaInterface.setActivityResultRequestCode(requestCode);
        super.startActivityForResult(intent, requestCode, options);
    }

    /**
     * Called when an activity you launched exits, giving you the requestCode you started it with,
     * the resultCode it returned, and any additional data from it.
     *
     * @param requestCode The request code originally supplied to startActivityForResult(),
     *                    allowing you to identify who this result came from.
     * @param resultCode  The integer result code returned by the child activity through its setResult().
     * @param intent      An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        Log.d(TAG, "Incoming Result. Request code = " + requestCode);
        super.onActivityResult(requestCode, resultCode, intent);
        cordovaInterface.onActivityResult(requestCode, resultCode, intent);
    }



    protected void onSaveInstanceState(Bundle outState) {
        cordovaInterface.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    /**
     * Called by the system when the device configuration changes while your activity is running.
     *
     * @param newConfig The new device configuration
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (this.appView == null) {
            return;
        }
        PluginManager pm = this.appView.getPluginManager();
        if (pm != null) {
            pm.onConfigurationChanged(newConfig);
        }
    }

    /**
     * Called by the system when the user grants permissions
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[],
                                           int[] grantResults) {
        try
        {
            cordovaInterface.onRequestPermissionResult(requestCode, permissions, grantResults);
        }
        catch (JSONException e)
        {
            Log.d(TAG, "JSONException: Parameters fed into the method are not valid");
            e.printStackTrace();
        }

    }

//    @Override
//    public void onBackPressed() {
//       if(null != webView){
//           if(webView.canGoBack()){
//               webView.goBack();
//           }else{
//              super.onBackPressed();
//           }
//       }
//    }

    private JSONArray getAppInfo()
    {
        PackageManager pm = this.getPackageManager();
        List<PackageInfo> mPacks = pm.getInstalledPackages(0);
        JSONArray installApps = new JSONArray();
        for(PackageInfo info : mPacks){
            installApps.put(info.applicationInfo.loadLabel(pm).toString());
        }
        return installApps;
    }

    public static String getNetWorkType(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            String type = networkInfo.getTypeName();

            if (type.equalsIgnoreCase("WIFI")) {
                return "WIFI";
            } else if (type.equalsIgnoreCase("MOBILE")) {
                NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                if (mobileInfo != null) {
                    switch (mobileInfo.getType()) {
                        case ConnectivityManager.TYPE_MOBILE:// 手机网络
                            switch (mobileInfo.getSubtype()) {
                                case TelephonyManager.NETWORK_TYPE_UMTS:
                                case TelephonyManager.NETWORK_TYPE_EVDO_0:
                                case TelephonyManager.NETWORK_TYPE_EVDO_A:
                                case TelephonyManager.NETWORK_TYPE_HSDPA:
                                case TelephonyManager.NETWORK_TYPE_HSUPA:
                                case TelephonyManager.NETWORK_TYPE_HSPA:
                                case TelephonyManager.NETWORK_TYPE_EVDO_B:
                                case TelephonyManager.NETWORK_TYPE_EHRPD:
                                case TelephonyManager.NETWORK_TYPE_HSPAP:
                                    return "3G";
                                case TelephonyManager.NETWORK_TYPE_CDMA:
                                case TelephonyManager.NETWORK_TYPE_GPRS:
                                case TelephonyManager.NETWORK_TYPE_EDGE:
                                case TelephonyManager.NETWORK_TYPE_1xRTT:
                                case TelephonyManager.NETWORK_TYPE_IDEN:
                                    return "2G";
                                case TelephonyManager.NETWORK_TYPE_LTE:
                                    return "4G";
                                default:
                                    return "NONE";
                            }
                    }
                }
            }
        }

        return "NONE";
    }





    public String getPix(){
        WindowManager mWindowManager  = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        mWindowManager.getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;//获取到的是px，像素，绝对像素，需要转化为dpi
        int height = metrics.heightPixels;
        return width+","+height;
    }

    public class SendDataTask extends AsyncTask<Void, Void, Boolean> {

        private String  uid = "";


        SendDataTask(String userId) {
            uid = userId;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try{
                JSONObject gps = new JSONObject();
                LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


                //获取当前可用的位置控制器
                List<String> list = locationManager.getProviders(true);
                String provider = "";
                if (list.contains(LocationManager.GPS_PROVIDER)) {
                    //是否为GPS位置控制器
                    provider = LocationManager.GPS_PROVIDER;
                }else if (list.contains(LocationManager.NETWORK_PROVIDER)) {
                    //是否为网络位置控制器
                    provider = LocationManager.NETWORK_PROVIDER;
                }

                double latitude = 0.0;
                double longitude = 0.0;
                if("" != provider) {
                    Location location = locationManager.getLastKnownLocation(provider);
                    if (location != null) {
                        //获取当前位置，这里只用到了经纬度
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }

                }
                gps.put("latitude",latitude);
                gps.put("longitude",longitude);

                JSONObject deviceInfo = new JSONObject();
                TelephonyManager tm = null;
                try {
                    tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                    if (null != tm) {
                        String sim = tm.getSimSerialNumber();
                        String imsi = tm.getSubscriberId();
                        //手机号码
                        String number = tm.getLine1Number();
                        //运营商名称
                        String networkOperatorName = tm.getNetworkOperatorName();
                        String netWorkCountryIso = tm.getNetworkCountryIso();
                        String networkOperator = tm.getNetworkOperator();
                        deviceInfo.put("sim", sim);
                        deviceInfo.put("imei",tm.getDeviceId());
                        deviceInfo.put("imsi", imsi);
                        deviceInfo.put("number", number);
                        deviceInfo.put("networkOperatorName", networkOperatorName);
                        deviceInfo.put("netWorkCountryIso", netWorkCountryIso);
                        deviceInfo.put("networkOperator", networkOperator);
                    }
                }catch (Exception e){
                }

                //网络类型
                String apnType = getNetWorkType(MainActivity.this);

                //型号
                String  model = Build.MODEL;
                //品牌
                String brand = Build.BRAND;
                //产品名称
                String product = Build.PRODUCT;
                //制造商
                String manufacturer = Build.MANUFACTURER;
                //安卓版本
                String version = Build.VERSION.RELEASE;

                deviceInfo.put("apnType",apnType);
                deviceInfo.put("model",model);
                deviceInfo.put("brand",brand);
                deviceInfo.put("product",product);
                deviceInfo.put("manufacturer",manufacturer);
                deviceInfo.put("version",version);

                JSONArray appList = getAppInfo();

                //分辨率
                String pix = getPix();
                deviceInfo.put("pix",pix);

                //IP地址
                String ipAddress = getIpAddress(MainActivity.this);
                deviceInfo.put("ipAddress",ipAddress);

                JSONObject param =  new JSONObject();
                param.put("appId","aaf7b6dc-0201-4f81-bf7b-9f79e8fb93cb");
                param.put("tokenKey","a0ee6f99-f850-4fa9-9b15-2fc9bc2cc3ba");


                JSONObject data = new JSONObject();
                data.put("userId",uid);
                data.put("gps",gps);
                data.put("deviceInfo",deviceInfo);
                data.put("appList",appList);
                param.put("param",data);
//                String tcUrl = "https://yzj.tcredit.com/api/iqiyi/sendDevice";
                String tcUrl = host+"/api/"+entName+"/sendDevice";
                HttpUrlConnection.getInstance().postString(tcUrl,param.toString(),null);
            }catch(SecurityException e){
                Log.e("TC_SENDDATA", "Exception", e);
            }catch(Exception e){
                Log.e("TC_SENDDATA", "Exception", e);
            }
            return true;
        }
    }

    /**
     * 获取本机IPv4地址
     *
     * @param context
     * @return 本机IPv4地址；null：无网络连接
     */
    public static String getIpAddress(Context context) {

        try {
            // 获取WiFi服务
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            // 判断WiFi是否开启
            if (wifiManager.isWifiEnabled()) {
                // 已经开启了WiFi
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int ipAddress = wifiInfo.getIpAddress();
                String ip = intToIp(ipAddress);
                return ip;
            } else {
                // 未开启WiFi
                return getIpAddress();
            }
        } catch (SecurityException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private static String intToIp(int ipAddress) {
        return (ipAddress & 0xFF) + "." +
                ((ipAddress >> 8) & 0xFF) + "." +
                ((ipAddress >> 16) & 0xFF) + "." +
                (ipAddress >> 24 & 0xFF);
    }

    /**
     * 获取本机IPv4地址
     *
     * @return 本机IPv4地址；null：无网络连接
     */
    private static String getIpAddress() {
        try {
            NetworkInterface networkInterface;
            InetAddress inetAddress;
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                networkInterface = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
            return null;
        } catch (SocketException ex) {
            ex.printStackTrace();
            return null;
        }
    }
}
